package com.king.login.filter;

import cn.hutool.core.util.StrUtil;
import com.king.login.security.LoginUser;
import com.king.platform.redis.RedisUtils;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import java.io.IOException;


@Component
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {
  @Autowired
  private RedisUtils redisUtils;

  @Override
  protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
    String token = request.getHeader("token");
    if (StrUtil.isEmpty(token)) {
      filterChain.doFilter(request, response);
      return;
    }
    //解析token
    String key = "user:1";
    System.out.println(key);
    //redis中获取用户信息
    LoginUser loginUser = (LoginUser) redisUtils.get(key);
    //存储验证用户信息
    UsernamePasswordAuthenticationToken auth = new UsernamePasswordAuthenticationToken(loginUser, null, null);
    SecurityContextHolder.getContext().setAuthentication(auth);

    filterChain.doFilter(request, response);
  }
}
